class Task < ActiveRecord::Base

  after_save :add_log
  
  hobo_model

  has_many :assignments
  has_many :users, :through => :assignments
  has_many :logs
  
  belongs_to :project
  belongs_to :task_kind
  belongs_to :task_status
  belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
  belongs_to :user
  
  set_creator_attr :user

  # --- Hobo Permissions --- #

  def creatable_by?(creator)
    creator == self and creator.administrator?
  end

  def updatable_by?(updater, new)
    updater == self 
  end

  def deletable_by?(deleter)
    true
  end

  def viewable_by?(viewer, field)
    true
  end
  
  protected
  
  def add_log
    if Task.exists?(self.id)
      current = Task.find(self.id)
      if self.owner != current.owner
        if current.owner == nil
          self.logs.create(:user_id => "1",:comment => "System: Assigned owner to #{self.owner.login}." )
        else
          self.logs.create(:user_id => "1",:comment => "System: Assigned owner from #{current.owner.login} to #{self.owner.login}." )
        end
      end
      if self.task_status != current.task_status
        if current.task_status == nil
          self.logs.create(:user_id => "1", :comment => "System: Task Status changed from none to #{self.task_status.name}.")
        else
          self.logs.create(:user_id => "1", :comment => "System: Task Status changed from #{current.task_status.name} to #{self.task_status.name}.")
        end
      end
    else
      self.logs.create(:user_id => "1", :task_id => self.id, :comment => "Created at #{Time.now}. ")
    end
  end
  
end
